<template>
  <div class="road-view-modal" @click.self="$emit('go-back')">
    <div class="road-view-page">
      <div class="road-container">
        <div class="road-header">
          <button @click="$emit('go-back')" class="back-button">✕ 关闭</button>
          <h2>车路数据</h2>
        </div>
      
      <div v-if="loading" class="loading">
        <p>正在加载车路数据...</p>
      </div>
      
      <div v-else-if="error" class="error">
        <p>{{ error }}</p>
      </div>
      
      <div v-else class="content-layout">
        <!-- Left Column: Points Data -->
        <div class="left-column">
          <h3 class="column-title">车路数据</h3>
          <div v-if="pointData.length === 0" class="empty">
            <p>暂无车路数据</p>
          </div>
          <div v-else class="points-grid">
            <div v-for="(point, index) in pointData" :key="index" class="point-card">
          <div class="point-header">
            <span v-if="point.maintDate" class="point-maint-date">
              {{ formatDate(point.maintDate) }}
            </span>
            <span class="point-type">
              <span v-if="point.type === 'repair'" class="badge repair">维修</span>
              <span v-else-if="point.type === 'maint'" class="badge maint">保养</span>
              <span v-else class="badge default">{{ point.type || '其他' }}</span>
            </span>
          </div>
          
          <div class="point-body">
            <div class="point-row">
              <span class="label">里程:</span>
              <span class="value">{{ point.mileage || '-' }} km</span>
            </div>
            
            
            <div v-if="point.date" class="point-row">
              <span class="label">日期:</span>
              <span class="value">{{ formatDate(point.date) }}</span>
            </div>
            
            <div v-if="point.s4Price" class="point-row">
              <span class="label">S4价格:</span>
              <span class="value">¥{{ point.s4Price }}</span>
            </div>
            
            <div v-if="point.zxcPrice" class="point-row">
              <span class="label">正兴价格:</span>
              <span class="value">¥{{ point.zxcPrice }}</span>
            </div>
            
            <div v-if="point.descList && point.descList.length > 0" class="point-row full-width">
              <span class="label">描述:</span>
              <div class="desc-list">
                <span v-for="(desc, idx) in point.descList" :key="idx" class="desc-item">
                  {{ desc }}
                </span>
              </div>
            </div>
            
            <div v-if="point.partList && point.partList.length > 0" class="point-row full-width">
              <span class="label">零件:</span>
              <div class="desc-list">
                <span v-for="(part, idx) in point.partList" :key="idx" class="desc-item">
                  {{ part.value || part.entity || part }}
                </span>
              </div>
            </div>
          </div>
          </div>
        </div>
      </div>
      
      <!-- Right Column: Maintenance Records -->
      <div class="right-column">
        <h3 class="column-title">保养记录</h3>
        <div v-if="maintRecords.length === 0" class="empty">
          <p>暂无保养记录</p>
        </div>
        <div v-else class="records-grid">
          <div v-for="(record, index) in maintRecords" :key="index" class="record-card">
            <div class="record-header">
              <span class="record-date">{{ formatDate(record.date) }}</span>
            </div>
            <div class="record-body">
              <div v-if="record.mileage" class="record-row">
                <span class="label">公里数:</span>
                <span class="value">{{ record.mileage }} km</span>
              </div>
              
              <div v-if="record.parts" class="record-row">
                <span class="label">零件:</span>
                <span class="value">{{ record.parts }}</span>
              </div>
              
              <div v-if="record.projects" class="record-row">
                <span class="label">项目:</span>
                <span class="value">{{ record.projects }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  </div>
</div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getUserCarHome, getMaintRecordList } from '../api/index.js'

const props = defineProps({
  userCarId: {
    type: String,
    required: true
  }
})

const emit = defineEmits(['go-back'])

const loading = ref(false)
const error = ref(null)
const pointData = ref([])
const maintRecords = ref([])

onMounted(async () => {
  loading.value = true
  error.value = null
  
  try {
    console.log('Fetching road data for userCarId:', props.userCarId)
    
    // Fetch point data
    const response = await getUserCarHome(props.userCarId)
    console.log('Road data response:', response)
    
    if (response.data && response.data.code === 0 && response.data.data) {
      // Extract point array from response - data structure is response.data.data.points.history
      const pointsData = response.data.data.points
      let rawPoints = []
      if (pointsData && pointsData.history && Array.isArray(pointsData.history)) {
        rawPoints = pointsData.history
      } else if (Array.isArray(pointsData)) {
        rawPoints = pointsData
      }
      
      // Process and map data with new fields
      const mappedPoints = rawPoints.map(item => ({
        ...item,
        // Calculate type field
        type: item.pointEnum === 'PART_REPLACE_RECORD' || item.pointEnum === 'PART_REPLACE_ALERT'
          ? 'repair'
          : 'maint'
      }))
      
      // Sort by date descending (newest first)
      pointData.value = mappedPoints.sort((a, b) => {
        const dateA = a.date || a.maintDate || 0
        const dateB = b.date || b.maintDate || 0
        return dateB - dateA
      })
      
      console.log('Point data:', pointData.value)
    } else {
      error.value = '获取车路数据失败'
      pointData.value = []
    }
    
    // Fetch maintenance records
    const maintResponse = await getMaintRecordList(props.userCarId, 'maint')
    console.log('Maintenance records response:', maintResponse)
    
    if (maintResponse.data && maintResponse.data.code === 0) {
      const recordList = maintResponse.data.data?.recordList || []
      maintRecords.value = recordList.map(item => ({
        date: item.date || item.maintDate,
        mileage: item.mileage,
        parts: item.partsNames,
        projects: item.details ? item.details.map(p => p.maintPartName).join(',') : ''
      }))
      console.log('Maintenance records:', maintRecords.value)
    }
  } catch (err) {
    console.error('Failed to load data:', err)
    error.value = err.message || '加载数据时发生错误'
    pointData.value = []
  } finally {
    loading.value = false
  }
})

function formatDate(timestamp) {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  return date.toLocaleDateString('zh-CN')
}
</script>

<style scoped>
.road-view-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 2rem;
}

.road-view-page {
  max-width: 1200px;
  max-height: 90vh;
  width: 100%;
  overflow: auto;
  margin: auto;
}

.road-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.2);
  padding: 1.5rem;
  max-height: 90vh;
  overflow-y: auto;
}

.road-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 1.5rem;
  padding-bottom: 1rem;
  border-bottom: 2px solid #e5e7eb;
}

.road-header h2 {
  color: #42b983;
  margin: 0;
}

.back-button {
  background-color: #dc3545;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: background-color 0.2s;
}

.back-button:hover {
  background-color: #c82333;
}

.loading, .empty, .error {
  text-align: center;
  padding: 2rem;
  color: #64748b;
}

.error {
  color: #dc3545;
}

.content-layout {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1.5rem;
  margin-top: 1rem;
}

.left-column,
.right-column {
  display: flex;
  flex-direction: column;
}

.column-title {
  color: #42b983;
  margin: 0 0 1rem 0;
  font-size: 1.1rem;
  padding-bottom: 0.5rem;
  border-bottom: 2px solid #e5e7eb;
}

.points-grid {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.records-grid {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.point-card {
  background: #f8fafc;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 1rem;
  transition: transform 0.2s, box-shadow 0.2s;
}

.point-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.point-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.75rem;
  padding-bottom: 0.75rem;
  border-bottom: 2px solid #e5e7eb;
}

.badge {
  display: inline-block;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.85rem;
  font-weight: bold;
}

.badge.repair {
  background-color: #fef3c7;
  color: #d97706;
}

.badge.maint {
  background-color: #dbeafe;
  color: #1e40af;
}

.badge.default {
  background-color: #e5e7eb;
  color: #4b5563;
}

.status {
  font-size: 0.85rem;
  font-weight: 500;
}

.status.done {
  color: #059669;
}

.status.pending {
  color: #dc2626;
}

.point-maint-date {
  font-size: 0.9rem;
  color: #64748b;
  font-weight: 500;
}

.point-body {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.point-row {
  display: flex;
  justify-content: space-between;
  padding: 0.25rem 0;
}

.point-row.full-width {
  flex-direction: column;
  gap: 0.25rem;
}

.label {
  color: #64748b;
  font-size: 0.9rem;
}

.value {
  color: #1e293b;
  font-weight: 500;
}

.desc-list {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.desc-item {
  font-size: 0.85rem;
  color: #4b5563;
}

.record-card {
  background: #f8fafc;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 1rem;
  transition: transform 0.2s, box-shadow 0.2s;
}

.record-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.record-header {
  margin-bottom: 0.75rem;
  padding-bottom: 0.75rem;
  border-bottom: 2px solid #42b983;
}

.record-date {
  font-size: 1rem;
  font-weight: bold;
  color: #42b983;
}

.record-body {
  display: flex;
  flex-direction: column;
  gap: 0.1rem;
}

.record-row {
  display: flex;
  justify-content: space-between;
  padding: 0.25rem 0;
}

.record-row.full-width {
  flex-direction: column;
  gap: 0.25rem;
}

.desc-content {
  word-break: break-all;
  word-wrap: break-word;
  white-space: pre-wrap;
  overflow-wrap: break-word;
  max-width: 100%;
}
</style>

